package filter

import (
	"fmt"
	"github.com/astaxie/beego/context"
	"myadmin/sys/cache/cacheinit"
	"myadmin/sys/cache/mapstore"
	"myadmin/sys/session"
	"myadmin/sys/sysmodels"
	"strings"
)

/*
登录验证
 */
//
func AuthLogin(ctx *context.Context) {
	fmt.Println("in authlogin")
	authtoken := ctx.Input.Header("Authorization")
	if authtoken == "" {
		Json403(ctx, "缺少验证token")
		return
	}
	//获取token
	ses := session.Ses.Get(authtoken)
	if ses == nil {
		Json403(ctx, "token失效")
		return
	}
	////限速设置
	//speed := mapstore.Get("speed")
	//fmt.Println("speed",speed)
	//if speed!=nil{
	//	sp:=speed.(int64)
	//	//fmt.Println(ses)
	//	//fmt.Println( ses.ActiveTime,sp, time.Now().Unix())
	//	if ses.ActiveTime+sp>time.Now().Unix(){
	//		session.Ses.UpdateTime("session",ses)
	//		Json400x(ctx,"请求频率过快",nil)
	//		return
	//	}
	//	session.Ses.UpdateTime(authtoken,ses)
	//}
	ctx.Input.SetData("BaseUser", ses.User)
	ctx.Input.SetData("Session", ses)
	//fmt.Println(authtoken,ses)

}

/*
权限验证
 */
func Auth(ctx *context.Context) {

	user_ := ctx.Input.GetData("BaseUser")
	// 获取角色
	user := user_.(sysmodels.SysUser)
	role := user.RoleName
	if role == "" {
		Json403(ctx, "您没有设置任何权限！")
		return
	}

	//设置后端用权限
	mapauthapi := mapstore.Get("roleAuthsApi")
	if mapauthapi == nil {
		mapauth := mapstore.Get("roleAuths")
		if mapauth == nil {
			mapauth = cacheinit.SetRoleAuth()
		}
		mapauthapi = cacheinit.SetRoleAuthApi(mapauth.(map[string][]string))
	}
	authsApi := mapauthapi.(map[string][]string)[role]

	method := strings.ToLower(ctx.Input.Method())
	url := strings.ToLower(ctx.Input.URL())
	reqUrl := strings.Join([]string{method, url}, ":")
	for _, v := range authsApi {
		if strings.HasPrefix(reqUrl, v) {
			goto end
		}
	}
	Json403(ctx, "没有该权限")
end:
	return
}

